const jwt = require("jsonwebtoken")
const fs = require("fs");
const path = require("path")
    //撒盐，加密时候混淆
const privateKey = fs.readFileSync(path.join(__dirname, 'tokenKey.pem'), "utf-8");
// const privateKey = 'zhengyu'

//生成token
//info也就是payload是需要存入token的信息
function createToken(info) {
    let token = jwt.sign(info, privateKey, { expiresIn: '1day' });
    return token
}

//验证Token
function verifyToken(token) {
    return new Promise((resolve, reject) => {
        jwt.verify(token, privateKey, (error, result) => {
            if (error) {
                if (error.name == 'TokenExpiredError') { //token过期
                    let str = {
                        code: 10086,
                        message: 'token过期'
                    }
                    return reject(str);
                } else if (error.name == 'JsonWebTokenError') { //无效的token
                    let str = {
                        code: 10086,
                        message: '无效的token'
                    }
                    return reject(str);
                } else if (error.name == 'UnauthorizedError') {
                    let str = {
                        code: 10086,
                        message: 'token未授权'
                    }
                    return reject(str);
                }
            } else {
                return resolve(result);
            }


        })


    })



}

module.exports = {
    createToken,
    verifyToken
}